import React, { useState, useEffect } from 'react'
import { useSearchParams } from 'react-router-dom';
import { cateList } from '../../https/index'
import { Swiper, Toast, TabBar, Popup, Button, Space } from 'antd-mobile';
import {
  GiftOutline,
  HeartOutline
} from 'antd-mobile-icons'
import { useDispatch } from 'react-redux'
import { addj, addgwc } from '../../store/login/index'
import { ddcreates, dzlist } from '../../https/index'
import '../../App.css'
import { useNavigate } from 'react-router-dom'
export default function ProductDetails() {
  const [searchParams, setSearchParams] = useSearchParams();
  const id = searchParams.get('id');
  const [list, setList] = useState([])
  const [images, setImages] = useState([])
  const [price, setPrice] = useState([])
  const dispatch = useDispatch()
  const [visible1, setVisible1] = useState(false)
  const [visible0, setVisible0] = useState(false)
  const [activeKey, setActiveKey] = useState('todo')
  const [status, setStatus] = useState('待发货')
  const [orderAmount, setOrderAmount] = useState('')
  const [tab, setTabs] = useState([])
  const [date, setDate] = useState(new Date())
  const [num, setNum] = useState(0)
  const [actions, setActions] = useState('')
  const [dizhi, setDizhi] = useState([])
  const [isAdding, setIsAdding] = useState(false) // 添加状态，用于显示加载
  const nav = useNavigate()
  const getList = async () => {
    const res = await cateList(id)
    setList(res.data.data)
    setImages(res.data.data[0].images)
    setPrice(res.data.data[0].price)
  }
  const getdizhi = async () => {
    const res = await dzlist(sessionStorage.getItem('logid'))
    setDizhi(res.data.list)
  }

  const ddje = () => {
    setOrderAmount(price * num)
  }

  useEffect(() => {
    getList()
    getdizhi()
  }, [])

  useEffect(() => {
    ddje()
  }, [num])

  const items = images.map((color, index) => (
    <Swiper.Item key={index}>
      <div
        style={{
          height: '60rem', display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          userSelect: 'none'
        }}
        onClick={() => {
          Toast.show(`你点击了卡片 ${index + 1}`)
        }}
      >
        <img src={color} style={{ width: '120rem' }} />
      </div>
    </Swiper.Item>
  ))

  const tabs = [
    {
      key: 'home',
      title: '商家',
      icon: <GiftOutline />
    },
    {
      key: 'message',
      title: '收藏',
      icon: <HeartOutline />
    }
  ]

  const dd = async () => {
    await ddcreates(list[0].name, list[0].description, list[0].price, list[0].userId, list[0].image, sessionStorage.getItem('logid'),
      status, orderAmount, tab, date, num, dizhi[0].provinceName, dizhi[0].cityName, dizhi[0].districtName, dizhi[0].detailAddress)
    setVisible1(false)
    setActions('')
    setNum(0)
    setTabs([])
  }

  const tabss = (items) => {
    setTabs(items)
    setActions(items)
  }


  // 完善加入购物车功能
  const add = () => {
    if (!list || list.length === 0) {
      Toast.show('商品信息加载中，请稍候')
      return
    }

    // 显示加载状态
    setIsAdding(true)

    // 添加延迟，模拟网络请求
    setTimeout(() => {
      try {
        // 获取当前商品信息
        const product = list[0]

        // 确保商品有ID
        if (!product.id) {
          throw new Error('商品ID不存在')
        }

        // 构建要添加到购物车的商品对象
        const cartItem = {
          name: list[0].name, description: list[0].description, price: list[0].price, userId: list[0].userId, image: list[0].image, logid: sessionStorage.getItem('logid'),
          status: status, orderAmount: orderAmount, Tabs: tab, date: date, num: num, provinceName: dizhi[0].provinceName, provinceName: dizhi[0].provinceName, cityName: dizhi[0].cityName,
          cityName: dizhi[0].cityName, districtName: dizhi[0].districtName, detailAddress: dizhi[0].detailAddress
        }

        // 调用redux action添加到购物车
        dispatch(addj({ id: new Date(), ...cartItem, num: 1 }))
        setVisible1(false)
        setActions('')
        setNum(0)
        setTabs([])

        // 显示成功提示
        Toast.show('已加入购物车')
        nav("/gou")
      } catch (error) {
        console.error('加入购物车失败:', error)
        Toast.show('加入购物车失败，请重试')
      } finally {
        // 隐藏加载状态
        setIsAdding(false)
      }
    }, 500)
  }

  return (
    <div style={{ height: '120rem', width: '120rem' }}>
      <div style={{ width: '120rem', height: '60rem' }}>
        <Swiper loop autoplay>
          {items}
        </Swiper>
      </div>
      <div>
        <div style={{ fontSize: '3rem' }}>
          {
            list.map((item, index) => {
              return (
                <div key={index} style={{ fontSize: '5rem' }}>
                  <p>{item.name}</p>
                  <p>{item.description}</p>
                </div>
              )
            })
          }
        </div>
      </div>
      <div style={{ width: '120rem', position: 'fixed', bottom: '0', backgroundColor: 'white' }}>
        <div style={{ display: 'flex', justifyContent: 'space-around' }}>
          <TabBar style={{ width: '30%' }}>
            {tabs.map(item => (
              <TabBar.Item key={item.key} icon={item.icon} title={item.title} />
            ))}
          </TabBar>
          <div style={{
            width: '34%', backgroundColor: 'yellow', color: 'black',
            textAlign: 'center', fontSize: '7rem', lineHeight: '13rem',
            borderRadius: '7rem'
          }} onClick={() => { setVisible0(true) }}>
            <span>{isAdding ? '添加中...' : '加入购物车'}</span>
          </div>
          <div style={{ width: '34%', backgroundColor: 'red', color: 'white', textAlign: 'center', fontSize: '5rem' }}>
            <p style={{ margin: '0', padding: '0' }}>￥{price}</p>
            <p style={{ margin: '0', padding: '0' }} onClick={() => { setVisible1(true) }}>立即购买</p>
          </div>
        </div>
      </div>
      <Popup
        visible={visible1}
        onMaskClick={() => {
          setVisible1(false)
        }}
        onClose={() => {
          setVisible1(false)
        }}
      // bodyStyle={{ height: '120rem' }}
      >
        <div style={{ marginBottom: '22rem' }}>
          <div>
            <span>型号</span>
            {
              list.map((item, index) => {
                return (
                  <div key={index}>
                    <Space wrap>
                      {
                        item.Tabs.map((items, indexs) => {
                          return (
                            <Button key={indexs} className={actions === items ? 'dds' : ''} onClick={() => { tabss(items) }}>{items}</Button>
                          )
                        })
                      }
                    </Space>
                  </div>
                )
              })
            }
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span>数量</span>
            <div>
              <button onClick={() => { if (num > 1) { setNum(num - 1) } }}>-</button>
              <span>{num}</span>
              <button onClick={() => { setNum(num + 1) }}>+</button>
            </div>
          </div>
        </div>
        <div style={{ position: 'fixed', bottom: '0', width: '120rem', padding: '0 2rem' }}>
          <div style={{ fontSize: '5rem' }}>
            订单金额：￥{orderAmount}
          </div>
          <Button block color='danger' size='large'
            onClick={dd}>
            立即支付
          </Button>
        </div>
      </Popup>
      <Popup
        visible={visible0}
        onMaskClick={() => {
          setVisible0(false)
        }}
        onClose={() => {
          setVisible0(false)
        }}
      // bodyStyle={{ height: '120rem' }}
      >
        <div style={{ marginBottom: '22rem' }}>
          <div>
            <span>型号</span>
            {
              list.map((item, index) => {
                return (
                  <div key={index}>
                    <Space wrap>
                      {
                        item.Tabs.map((items, indexs) => {
                          return (
                            <Button key={indexs} className={actions === items ? 'dds' : ''} onClick={() => { tabss(items) }}>{items}</Button>
                          )
                        })
                      }
                    </Space>
                  </div>
                )
              })
            }
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span>数量</span>
            <div>
              <button onClick={() => { if (num > 1) { setNum(num - 1) } }}>-</button>
              <span>{num}</span>
              <button onClick={() => { setNum(num + 1) }}>+</button>
            </div>
          </div>
        </div>
        <div style={{ position: 'fixed', bottom: '0', width: '120rem', padding: '0 2rem' }}>
          <div style={{ fontSize: '5rem' }}>
            订单金额：￥{orderAmount}
          </div>
          <Button block color='danger' size='large'
            onClick={add}>
            加入购物车
          </Button>
        </div>
      </Popup>
    </div>
  )
}
